package com.jzo2o.customer.service.impl;

import com.jzo2o.common.utils.BeanUtils;
import com.jzo2o.common.utils.ObjectUtils;
import com.jzo2o.customer.enums.CertificationStatusEnum;
import com.jzo2o.customer.mapper.WorkerCertificationAuditMapper;
import com.jzo2o.customer.model.domain.WorkerCertification;
import com.jzo2o.customer.mapper.WorkerCertificationMapper;
import com.jzo2o.customer.model.domain.WorkerCertificationAudit;
import com.jzo2o.customer.model.dto.request.WorkerCertificationAuditAddReqDTO;
import com.jzo2o.customer.model.dto.response.RejectReasonResDTO;
import com.jzo2o.customer.model.dto.response.WorkerCertificationAuditResDTO;
import com.jzo2o.customer.service.IWorkerCertificationAuditService;
import com.jzo2o.customer.service.IWorkerCertificationService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.jzo2o.mvc.utils.UserContext;
import lombok.RequiredArgsConstructor;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

/**
 * <p>
 * 服务人员认证信息表 服务实现类
 * </p>
 *
 * @author Echo
 * @since 2025-03-07
 */
@Service
@RequiredArgsConstructor
public class WorkerCertificationServiceImpl extends ServiceImpl<WorkerCertificationMapper, WorkerCertification> implements IWorkerCertificationService {
    private final IWorkerCertificationAuditService auditService;
    /**
     * 服务人员申请认证信息
     * @param dto
     */
    @Override
    @Transactional
    public void saveCertification(WorkerCertificationAuditAddReqDTO dto) {
        Long userId = UserContext.currentUserId();
        WorkerCertification certification = BeanUtils.copyBean(dto, WorkerCertification.class);
        certification.setId(userId);
        // 提交申请后设置为认证中
        certification.setCertificationStatus(CertificationStatusEnum.PROGRESSING.getStatus());
        // 设置认证状态为认证中
        certification.setCertificationStatus(CertificationStatusEnum.PROGRESSING.getStatus());
        save(certification);
        dto.setServeProviderId(userId);
        // 保存服务人员认证信息到审核表
        auditService.saveCertification(dto);
    }

    /**
     * 查询驳回原因
     * @return
     */
    @Override
    public RejectReasonResDTO queryRejectedReason() {
        Long userId = UserContext.currentUserId();
        // 查询服务人员认证失败状态下的失败原因
        WorkerCertificationAudit audit = auditService.lambdaQuery()
                .eq(WorkerCertificationAudit::getServeProviderId, userId)
                .eq(WorkerCertificationAudit::getCertificationStatus, CertificationStatusEnum.FAIL.getStatus())
                .one();
        if (ObjectUtils.isNotEmpty(audit)) {
            return BeanUtils.copyBean(audit, RejectReasonResDTO.class);
        }
        return null;
    }
}
